package com.mvc.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.mvc.entity.StrutsBean;

public class XmlParse {
	
	public static Map<String, StrutsBean> parse(String xmlpath) {
		
		SAXReader reader = new SAXReader();
		
		Map<String, StrutsBean> map = new HashMap<String, StrutsBean>();
		
		try {
			Document document = reader.read(new File(xmlpath));
			
			Element rootEle = document.getRootElement();
			
			Iterator<?> itAction = rootEle.elementIterator("action");
			while(itAction.hasNext()) {
				StrutsBean bean = new StrutsBean();
				Element actionEle = (Element) itAction.next();
				String name = actionEle.attributeValue("name");
				String actionClass = actionEle.attributeValue("class");
				String path = actionEle.attributeValue("path");
				
				bean.setName(name);
				bean.setActionClass(actionClass);
				bean.setPath(path);
				
				Iterator<?> itForward = actionEle.elementIterator("forward");
				Map<String, String> forwardMap = new HashMap<String, String>();
				while(itForward.hasNext()) {
					Element forwardEle = (Element) itForward.next();
					String url = forwardEle.attributeValue("url");
					String value = forwardEle.attributeValue("value");
					
					forwardMap.put(url, value);
				}
				bean.setForwards(forwardMap);
				
				Iterator<?> itEntitys = rootEle.elementIterator("entitys");
				while(itEntitys.hasNext()) {
					Element entitysEle = (Element)itEntitys.next();
					Iterator<?> itEntity = entitysEle.elementIterator("entity");
					while(itEntity.hasNext()) {
						Element entityEle = (Element)itEntity.next();
						String entityName = entityEle.attributeValue("name");
						String entityClass = entityEle.attributeValue("class");
						if(name.equals(entityName)) {
							bean.setEntityClass(entityClass);
						}
					}
				}
				map.put(path, bean);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
}
